{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8b6f4aa6b1b5"
      },
      "source": [
        "**Copyright 2021 The TensorFlow Authors.**"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "mEE8NFIMSGO-"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MfBg1C5NB3X0"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://www.tensorflow.org/model_optimization/guide/combine/pqat_example\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/model-optimization/blob/master/tensorflow_model_optimization/g3doc/guide/combine/pqat_example.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/model-optimization/blob/master/tensorflow_model_optimization/g3doc/guide/combine/pqat_example.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View on GitHub</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://storage.googleapis.com/tensorflow_docs/model-optimization/tensorflow_model_optimization/g3doc/guide/combine/pqat_example.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "SyiSRgdtSGPC"
      },
      "source": [
        "# Pruning preserving quantization aware training (PQAT) Keras example"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dKnJyAaASGPD"
      },
      "source": [
        "## Overview\n",
        "\n",
        "This is an end to end example showing the usage of the **pruning preserving quantization aware training (PQAT)** API, part of the TensorFlow Model Optimization Toolkit's collaborative optimization pipeline.\n",
        "\n",
        "### Other pages\n",
        "\n",
        "For an introduction to the pipeline and other available techniques, see the [collaborative optimization overview page](https://www.tensorflow.org/model_optimization/guide/combine/collaborative_optimization).\n",
        "\n",
        "### Contents\n",
        "\n",
        "In the tutorial, you will:\n",
        "\n",
        "1. Train a `tf.keras` model for the MNIST dataset from scratch.\n",
        "2. Fine-tune the model with pruning, using the sparsity API, and see the accuracy.\n",
        "3. Apply QAT and observe the loss of sparsity.\n",
        "4. Apply PQAT and observe that the sparsity applied earlier has been preserved.\n",
        "5. Generate a TFLite model and observe the effects of applying PQAT on it.\n",
        "6. Compare the achieved PQAT model accuracy with a model quantized using post-training quantization."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RgcQznnZSGPE"
      },
      "source": [
        "## Setup\n",
        "\n",
        "You can run this Jupyter Notebook in your local [virtualenv](https://www.tensorflow.org/install/pip?lang=python3#2.-create-a-virtual-environment-recommended) or [colab](https://colab.sandbox.google.com/). For details of setting up dependencies, please refer to the [installation guide](https://www.tensorflow.org/model_optimization/guide/install). "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "3asgXMqnSGPE"
      },
      "outputs": [],
      "source": [
        "! pip install -q tensorflow-model-optimization"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "gL6JiLXkSGPI"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf\n",
        "\n",
        "import numpy as np\n",
        "import tempfile\n",
        "import zipfile\n",
        "import os"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dKzOfl5FSGPL"
      },
      "source": [
        "## Train a tf.keras model for MNIST without pruning"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "w7Fd6jZ7SGPL"
      },
      "outputs": [],
      "source": [
        "# Load MNIST dataset\n",
        "mnist = tf.keras.datasets.mnist\n",
        "(train_images, train_labels), (test_images, test_labels) = mnist.load_data()\n",
        "\n",
        "# Normalize the input image so that each pixel value is between 0 to 1.\n",
        "train_images = train_images / 255.0\n",
        "test_images  = test_images / 255.0\n",
        "\n",
        "model = tf.keras.Sequential([\n",
        "  tf.keras.layers.InputLayer(input_shape=(28, 28)),\n",
        "  tf.keras.layers.Reshape(target_shape=(28, 28, 1)),\n",
        "  tf.keras.layers.Conv2D(filters=12, kernel_size=(3, 3),\n",
        "                         activation=tf.nn.relu),\n",
        "  tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),\n",
        "  tf.keras.layers.Flatten(),\n",
        "  tf.keras.layers.Dense(10)\n",
        "])\n",
        "\n",
        "# Train the digit classification model\n",
        "model.compile(optimizer='adam',\n",
        "              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        "              metrics=['accuracy'])\n",
        "\n",
        "model.fit(\n",
        "    train_images,\n",
        "    train_labels,\n",
        "    validation_split=0.1,\n",
        "    epochs=10\n",
        ")"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rBOQ8MeESGPO"
      },
      "source": [
        "### Evaluate the baseline model and save it for later usage"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "HYulekocSGPP"
      },
      "outputs": [],
      "source": [
        "_, baseline_model_accuracy = model.evaluate(\n",
        "    test_images, test_labels, verbose=0)\n",
        "\n",
        "print('Baseline test accuracy:', baseline_model_accuracy)\n",
        "\n",
        "_, keras_file = tempfile.mkstemp('.h5')\n",
        "print('Saving model to: ', keras_file)\n",
        "tf.keras.models.save_model(model, keras_file, include_optimizer=False)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "cWPgcnjKSGPR"
      },
      "source": [
        "## Prune and fine-tune the model to 50% sparsity"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Y2wKK7w9SGPS"
      },
      "source": [
        "Apply the `prune_low_magnitude()` API to prune the whole pre-trained model to demonstrate and observe its effectiveness in reducing the model size when applying zip, while maintaining accuracy. For how best to use the API to achieve the best compression rate while maintaining your target accuracy, refer to the [pruning comprehensive guide](https://www.tensorflow.org/model_optimization/guide/pruning/comprehensive_guide)."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ea40z522SGPT"
      },
      "source": [
        "### Define the model and apply the sparsity API"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7aOB5vjOZMTS"
      },
      "source": [
        "The model needs to be pre-trained before using the sparsity API."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "OzqKKt0mSGPT"
      },
      "outputs": [],
      "source": [
        "import tensorflow_model_optimization as tfmot\n",
        "\n",
        "prune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude\n",
        "\n",
        "pruning_params = {\n",
        "      'pruning_schedule': tfmot.sparsity.keras.ConstantSparsity(0.5, begin_step=0, frequency=100)\n",
        "  }\n",
        "\n",
        "callbacks = [\n",
        "  tfmot.sparsity.keras.UpdatePruningStep()\n",
        "]\n",
        "\n",
        "pruned_model = prune_low_magnitude(model, **pruning_params)\n",
        "\n",
        "# Use smaller learning rate for fine-tuning\n",
        "opt = tf.keras.optimizers.Adam(learning_rate=1e-5)\n",
        "\n",
        "pruned_model.compile(\n",
        "  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        "  optimizer=opt,\n",
        "  metrics=['accuracy'])\n",
        "\n",
        "pruned_model.summary()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "ev4MyClmSGPW"
      },
      "source": [
        "### Fine-tune the model and evaluate the accuracy against baseline"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vQoy9CcASGPX"
      },
      "source": [
        "Fine-tune the model with pruning for 3 epochs."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "jn29-coXSGPX"
      },
      "outputs": [],
      "source": [
        "# Fine-tune model\n",
        "pruned_model.fit(\n",
        "  train_images,\n",
        "  train_labels,\n",
        "  epochs=3,\n",
        "  validation_split=0.1,\n",
        "  callbacks=callbacks)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "198b9e9ce00b"
      },
      "source": [
        "Define helper functions to calculate and print the sparsity of the model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "69468934028c"
      },
      "outputs": [],
      "source": [
        "def print_model_weights_sparsity(model):\n",
        "\n",
        "    for layer in model.layers:\n",
        "        if isinstance(layer, tf.keras.layers.Wrapper):\n",
        "            weights = layer.trainable_weights\n",
        "        else:\n",
        "            weights = layer.weights\n",
        "        for weight in weights:\n",
        "            # ignore auxiliary quantization weights\n",
        "            if \"quantize_layer\" in weight.name:\n",
        "                continue\n",
        "            weight_size = weight.numpy().size\n",
        "            zero_num = np.count_nonzero(weight == 0)\n",
        "            print(\n",
        "                f\"{weight.name}: {zero_num/weight_size:.2%} sparsity \",\n",
        "                f\"({zero_num}/{weight_size})\",\n",
        "            )"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "abc304948a53"
      },
      "source": [
        "Check that the model was correctly pruned. We need to strip the pruning wrapper first."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "a3fada83ffd7"
      },
      "outputs": [],
      "source": [
        "stripped_pruned_model = tfmot.sparsity.keras.strip_pruning(pruned_model)\n",
        "\n",
        "print_model_weights_sparsity(stripped_pruned_model)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dvaZKoxtTORx"
      },
      "source": [
        "For this example, there is minimal loss in test accuracy after pruning, compared to the baseline."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "bE7MxpWLTaQ1"
      },
      "outputs": [],
      "source": [
        "_, pruned_model_accuracy = pruned_model.evaluate(\n",
        "  test_images, test_labels, verbose=0)\n",
        "\n",
        "print('Baseline test accuracy:', baseline_model_accuracy)\n",
        "print('Pruned test accuracy:', pruned_model_accuracy)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VXfPMa6ISGPd"
      },
      "source": [
        "## Apply QAT and PQAT and check effect on model sparsity in both cases"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1zr_QIhcUeuC"
      },
      "source": [
        "Next, we apply both QAT and pruning-preserving QAT (PQAT) on the pruned model and observe that PQAT preserves sparsity on your pruned model. Note that we stripped pruning wrappers from your pruned model with `tfmot.sparsity.keras.strip_pruning` before applying PQAT API."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4h6tSvMzSGPd"
      },
      "outputs": [],
      "source": [
        "# QAT\n",
        "qat_model = tfmot.quantization.keras.quantize_model(stripped_pruned_model)\n",
        "\n",
        "qat_model.compile(optimizer='adam',\n",
        "              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        "              metrics=['accuracy'])\n",
        "print('Train qat model:')\n",
        "qat_model.fit(train_images, train_labels, batch_size=128, epochs=1, validation_split=0.1)\n",
        "\n",
        "# PQAT\n",
        "quant_aware_annotate_model = tfmot.quantization.keras.quantize_annotate_model(\n",
        "              stripped_pruned_model)\n",
        "pqat_model = tfmot.quantization.keras.quantize_apply(\n",
        "              quant_aware_annotate_model,\n",
        "              tfmot.experimental.combine.Default8BitPrunePreserveQuantizeScheme())\n",
        "\n",
        "pqat_model.compile(optimizer='adam',\n",
        "              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n",
        "              metrics=['accuracy'])\n",
        "print('Train pqat model:')\n",
        "pqat_model.fit(train_images, train_labels, batch_size=128, epochs=1, validation_split=0.1)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "8e90c14cce8d"
      },
      "outputs": [],
      "source": [
        "print(\"QAT Model sparsity:\")\n",
        "print_model_weights_sparsity(qat_model)\n",
        "print(\"PQAT Model sparsity:\")\n",
        "print_model_weights_sparsity(pqat_model)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2877629dd054"
      },
      "source": [
        "## See compression benefits of PQAT model\n",
        "\n",
        "Define helper function to get zipped model file."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "b72869768986"
      },
      "outputs": [],
      "source": [
        "def get_gzipped_model_size(file):\n",
        "  # It returns the size of the gzipped model in kilobytes.\n",
        "\n",
        "  _, zipped_file = tempfile.mkstemp('.zip')\n",
        "  with zipfile.ZipFile(zipped_file, 'w', compression=zipfile.ZIP_DEFLATED) as f:\n",
        "    f.write(file)\n",
        "\n",
        "  return os.path.getsize(zipped_file)/1000"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "a1ef78df5740"
      },
      "source": [
        "Since this is a small model, the difference between the two models isn't very noticeable. Applying pruning and PQAT to a bigger production model would yield a more significant compression."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "057965bfae3d"
      },
      "outputs": [],
      "source": [
        "# QAT model\n",
        "converter = tf.lite.TFLiteConverter.from_keras_model(qat_model)\n",
        "converter.optimizations = [tf.lite.Optimize.DEFAULT]\n",
        "qat_tflite_model = converter.convert()\n",
        "qat_model_file = 'qat_model.tflite'\n",
        "# Save the model.\n",
        "with open(qat_model_file, 'wb') as f:\n",
        "    f.write(qat_tflite_model)\n",
        "    \n",
        "# PQAT model\n",
        "converter = tf.lite.TFLiteConverter.from_keras_model(pqat_model)\n",
        "converter.optimizations = [tf.lite.Optimize.DEFAULT]\n",
        "pqat_tflite_model = converter.convert()\n",
        "pqat_model_file = 'pqat_model.tflite'\n",
        "# Save the model.\n",
        "with open(pqat_model_file, 'wb') as f:\n",
        "    f.write(pqat_tflite_model)\n",
        "    \n",
        "print(\"QAT model size: \", get_gzipped_model_size(qat_model_file), ' KB')\n",
        "print(\"PQAT model size: \", get_gzipped_model_size(pqat_model_file), ' KB')"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "286cd588785a"
      },
      "source": [
        "## See the persistence of accuracy from TF to TFLite\n",
        "\n",
        "Define a helper function to evaluate the TFLite model on the test dataset."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "8808bb8628bd"
      },
      "outputs": [],
      "source": [
        "def eval_model(interpreter):\n",
        "  input_index = interpreter.get_input_details()[0][\"index\"]\n",
        "  output_index = interpreter.get_output_details()[0][\"index\"]\n",
        "\n",
        "  # Run predictions on every image in the \"test\" dataset.\n",
        "  prediction_digits = []\n",
        "  for i, test_image in enumerate(test_images):\n",
        "    if i % 1000 == 0:\n",
        "      print(f\"Evaluated on {i} results so far.\")\n",
        "    # Pre-processing: add batch dimension and convert to float32 to match with\n",
        "    # the model's input data format.\n",
        "    test_image = np.expand_dims(test_image, axis=0).astype(np.float32)\n",
        "    interpreter.set_tensor(input_index, test_image)\n",
        "\n",
        "    # Run inference.\n",
        "    interpreter.invoke()\n",
        "\n",
        "    # Post-processing: remove batch dimension and find the digit with highest\n",
        "    # probability.\n",
        "    output = interpreter.tensor(output_index)\n",
        "    digit = np.argmax(output()[0])\n",
        "    prediction_digits.append(digit)\n",
        "\n",
        "  print('\\n')\n",
        "  # Compare prediction results with ground truth labels to calculate accuracy.\n",
        "  prediction_digits = np.array(prediction_digits)\n",
        "  accuracy = (prediction_digits == test_labels).mean()\n",
        "  return accuracy"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "dd9e954bd826"
      },
      "source": [
        "You evaluate the model, which has been pruned and quantized, and then see the accuracy from TensorFlow persists in the TFLite backend."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4eaf0160ea09"
      },
      "outputs": [],
      "source": [
        "interpreter = tf.lite.Interpreter(pqat_model_file)\n",
        "interpreter.allocate_tensors()\n",
        "\n",
        "pqat_test_accuracy = eval_model(interpreter)\n",
        "\n",
        "print('Pruned and quantized TFLite test_accuracy:', pqat_test_accuracy)\n",
        "print('Pruned TF test accuracy:', pruned_model_accuracy)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "26dec6d57704"
      },
      "source": [
        "## Apply post-training quantization and compare to PQAT model\n",
        "\n",
        "Next, we use normal post-training quantization (no fine-tuning) on the pruned model and check its accuracy against the PQAT model. This demonstrates why you would need to use PQAT to improve the quantized model's accuracy.\n",
        "\n",
        "First, define a generator for the callibration dataset from the first 1000 training images."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "e92771026b96"
      },
      "outputs": [],
      "source": [
        "def mnist_representative_data_gen():\n",
        "  for image in train_images[:1000]:  \n",
        "    image = np.expand_dims(image, axis=0).astype(np.float32)\n",
        "    yield [image]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "085aa0dbc8a8"
      },
      "source": [
        "Quantize the model and compare accuracy to the previously acquired PQAT model. Note that the model quantized with fine-tuning achieves higher accuracy."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "0c913c4d4f9b"
      },
      "outputs": [],
      "source": [
        "converter = tf.lite.TFLiteConverter.from_keras_model(stripped_pruned_model)\n",
        "converter.optimizations = [tf.lite.Optimize.DEFAULT]\n",
        "converter.representative_dataset = mnist_representative_data_gen\n",
        "post_training_tflite_model = converter.convert()\n",
        "post_training_model_file = 'post_training_model.tflite'\n",
        "# Save the model.\n",
        "with open(post_training_model_file, 'wb') as f:\n",
        "    f.write(post_training_tflite_model)\n",
        "    \n",
        "# Compare accuracy\n",
        "interpreter = tf.lite.Interpreter(post_training_model_file)\n",
        "interpreter.allocate_tensors()\n",
        "\n",
        "post_training_test_accuracy = eval_model(interpreter)\n",
        "\n",
        "print('PQAT TFLite test_accuracy:', pqat_test_accuracy)\n",
        "print('Post-training (no fine-tuning) TF test accuracy:', post_training_test_accuracy)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "422b323172c5"
      },
      "source": [
        "## Conclusion"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7JhbpowqSGP1"
      },
      "source": [
        "In this tutorial, you learned how to create a model, prune it using the sparsity API, and apply the sparsity-preserving quantization aware training (PQAT) to preserve sparsity while using QAT. The final PQAT model was compared to the QAT one to show that the sparsity is preserved in the former and lost in the latter. Next, the models were converted to TFLite to show the compression benefits of chaining pruning and PQAT model optimization techniques and the TFLite model was evaluated to ensure that the accuracy persists in the TFLite backend. Finally, the PQAT model was compared to a quantized pruned model achieved using the post-training quantization API to demonstrate the advantage of PQAT in recovering the accuracy loss from normal quantization."
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "pqat_example.ipynb",
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
